package org.lous.lax;


import java.io.IOException;
import java.io.Writer;

/**
 * A Lax output stream
 * TODO: support parameters
 * TODO: support escaping
 * TODO: meta tags
 */
public class LaxOut
{

  // stream instance:
  private Writer dest;
  private int indentLevel;
  private String indentString;

  {
    indentLevel = 0;
    indentString = "  ";
  }


  public LaxOut(Writer dest) throws IOException
  {
    if (null == dest) return;
    this.dest = dest;
    addMeta("xml version='1.0' encoding='UTF-8'");
  }

  public void addTag(String name, String value) throws IOException
  {
    startTag(name);
    addData(value);
    endTag(name);
  }
  public void addTag(String name, int value) throws IOException
  {
    addTag(name, Integer.toString(value));
  }


  public void addData(String data) throws IOException
  {
    indent();
    dest.write(data);
  }

  public void startTag(String name) throws IOException
  {
    indent();
    dest.write("<"+name+">");
    indentLevel++;
  }


  public void endTag(String name) throws IOException
  {
    indentLevel--;
    indent();
    dest.write("</"+name+">");
  }


  public void addComment(String content) throws IOException
  {
    addComment(content, true);
  }

  public void addComment(String content, Boolean linebreak) throws IOException
  {
    if (linebreak){
      indent();
    }
    //TODO: escape content-end in data
    dest.write("<!-- "+content+" -->");
  }


  public void addMeta(String content) throws IOException
  {
    //TODO: escape content-end in data
    dest.write("<?"+content+"?>\n");

  }


  private void indent() throws IOException
  {
    dest.write("\n");
    if (indentLevel<0) indentLevel = 0;
    for (int i=0; i<this.indentLevel; i++){
      dest.write(this.indentString);
    }
  }

}